/*
    uthash demo source codes
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include "uthash.h"

typedef struct
{
    int key;
    int val;
    UT_hash_handle hh;
} UtHashItem;

UtHashItem *g_uthashItemTbl = NULL;

void AddItem(int key, int val)
{
    UtHashItem *ins = NULL;

    HASH_FIND(hh, g_uthashItemTbl, &key, sizeof(key), ins);
    if (ins != NULL)
    {
        ins->val = val;
        return;
    }

    ins = (UtHashItem *)malloc(sizeof(*ins));
    memset(ins, 0, sizeof(*ins));
    ins->key = key;
    ins->val = val;

    HASH_ADD(hh, g_uthashItemTbl, key, sizeof(key), ins);
}

void DelItem(UtHashItem *item)
{
    HASH_DELETE(hh, g_uthashItemTbl, item);
    free(item);
}

UtHashItem *FindItem(int key)
{
    UtHashItem *ins = NULL;

    HASH_FIND(hh, g_uthashItemTbl, &key, sizeof(key), ins);
    if (ins != NULL)
    {
        return ins;
    }
    return NULL;
}

int CompareItem(UtHashItem *a, UtHashItem *b)
{
    return a->key < b->key;
}

void SortItem()
{
    HASH_SRT(hh, g_uthashItemTbl, CompareItem);
}

void EchoItem()
{
    UtHashItem *el = NULL;
    UtHashItem *tmp = NULL;

    HASH_ITER(hh, g_uthashItemTbl, el, tmp)
    {
        printf("cur key[%d], val[%d]\n", el->key, el->val);
    }
}

int main()
{
    int key = 0;
    int val = 0;
    UtHashItem *ins = NULL;

    key = 1;
    val = 2;
    AddItem(key, val);

    key = 2;
    val = 3;
    AddItem(key, val);

    key = 1;
    ins = FindItem(key);
    printf("find item, k[%d]v[%d]\n", ins->key, ins->val);

    DelItem(ins);

    key = 1;
    ins = FindItem(key);

    int i = 0;
    for (i = 1; i < 5; i++)
    {
        key = 2 + i;
        val = 3 + i;
        AddItem(key, val);
    }

    printf("before sort\n");
    EchoItem();

    SortItem();

    printf("after sort\n");
    EchoItem();
    return 0;
}